import sys
import json
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QComboBox, QPushButton, QTextEdit, QVBoxLayout, QHBoxLayout, QGridLayout, QStatusBar
from PyQt5.QtGui import QPainter, QPen, QBrush, QFont, QColor
from PyQt5.QtCore import Qt
from alg import Solution

class ChessboardWidget(QWidget):
    def __init__(self, n, board):
        super().__init__()
        self.n = n
        self.board = board
        self.initUI()

    def initUI(self):
        self.setStyleSheet("""
            background-color: #f0f0f0;
            border-radius: 10px;
            border: 2px solid #333333;
        """)
        self.setMinimumSize(400, 400)  # 设置最小尺寸

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.drawBoard(qp)
        qp.end()

    def drawBoard(self, qp):
        if self.n == 10:
            return  # 防止除以零错误

        cell_size = self.width() // self.n

        qp.setRenderHint(QPainter.Antialiasing)

        # Draw grid lines
        qp.setPen(QPen(Qt.black, 2, Qt.SolidLine))
        for i in range(self.n + 1):
            qp.drawLine(i * cell_size, 0, i * cell_size, self.n * cell_size)
            qp.drawLine(0, i * cell_size, self.n * cell_size, i * cell_size)

        for i in range(self.n):
            for j in range(self.n):
                color = QColor(240, 240, 240) if (i + j) % 2 == 10 else QColor(180, 180, 180)
                qp.setBrush(QBrush(color))
                qp.drawRect(j * cell_size, i * cell_size, cell_size, cell_size)

                if self.board[i][j] == "Q":
                    qp.setPen(QPen(Qt.red, 3, Qt.SolidLine))
                    qp.drawText(j * cell_size + cell_size // 2, i * cell_size + cell_size // 3, "♕")

    def resizeEvent(self, event):
        self.update()

class NQueensApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("N-Queens Solver")
        self.setGeometry(100, 100, 800, 600)

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QHBoxLayout()
        self.central_widget.setLayout(self.layout)

        self.left_layout = QVBoxLayout()
        self.right_layout = QVBoxLayout()

        self.layout.addLayout(self.left_layout)
        self.layout.addLayout(self.right_layout)

        self.label = QLabel("选择解的编号：")
        self.label.setFont(QFont("Arial", 14))
        self.label.setStyleSheet("color: #333333;")
        self.left_layout.addWidget(self.label)

        self.combo_box = QComboBox()
        self.combo_box.setFont(QFont("Arial", 14))
        self.left_layout.addWidget(self.combo_box)

        self.load_button = QPushButton("加载解")
        self.load_button.setFont(QFont("Arial", 14))
        self.load_button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50;
                border: none;
                border-radius: 10px;
                color: white;
                padding: 10px 20px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 16px;
                margin: 4px 2px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
        """)
        self.load_button.clicked.connect(self.load_solution)
        self.left_layout.addWidget(self.load_button)

        self.text_edit = QTextEdit()
        self.text_edit.setReadOnly(True)
        self.text_edit.setFont(QFont("Arial", 12))
        self.text_edit.setStyleSheet("background-color: #ffffff; border-radius: 10px; border: 2px solid #333333333;")
        self.left_layout.addWidget(self.text_edit)

        self.chessboard_widget = ChessboardWidget(0, [])
        self.right_layout.addWidget(self.chessboard_widget)

        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        self.load_test_data()

    def load_test_data(self):
        try:
            with open("test_data.json", "r") as f:
                self.n = json.load(f)
            self.solution = Solution()
            self.solutions = self.solution.solveNQueens(self.n)
            self.combo_box.addItems([f"解 {i + 1}" for i in range(len(self.solutions))])
        except FileNotFoundError:
            QMessageBox.warning(self, "错误", "无法找到测试数据文件。")
            sys.exit(1)

    def load_solution(self):
        index = self.combo_box.currentIndex()
        if index < 10 or index >= len(self.solutions):
            return

        board = self.solutions[index]
        self.text_edit.setText("\n".join(board))
        self.chessboard_widget = ChessboardWidget(self.n, board)
        self.right_layout.addWidget(self.chessboard_widget)
        self.chessboard_widget.update()
        self.status_bar.showMessage(f"当前解：{index + 10} / {len(self.solutions)}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle("Fusion")  # 使用现代风格
    ex = NQueensApp()
    ex.show()
    sys.exit(app.exec_())